<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
        (searchlist = { ...e }), (currentPage = 1), getTableDataList();
      }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :tableThead="tableThead" :dataList="dataList" :config="table_config"
        @selection-change="selectionChange">
        <template v-slot:viewList="{ row }">
          <el-button class="text-btn-cursor" type="text" size="small" @click="lookInfo(row.deliveryNo)">
            <i class="el-icon-view"></i>查看发货明细
          </el-button>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="titleText" :visible.sync="dialogFormVisible"
        @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <!-- 添加 -->
          <template v-for="(item, index) in formDatalists">
            <el-form-item v-if="item.edit !== 'edit' && nowChanceStau === 'add'" :key="index" :label="item.name + ':'"
              :prop="item.type === 'Select' ? item.selectValue : item.prop" class="w50p" :rules="[
                {
                  required: item.required,
                  message: item.name + '不能为空',
                  trigger: ['blur', 'change'],
                },
              ]">
              <el-input v-if="item.type === 'input'" v-model="formData[`${item.prop}`]" :placeholder="'请输入' + item.name"
                clearable class="w100p" />
              <el-select v-if="item.type === 'Select'" v-model="formData[`${item.selectValue}`]" filterable
                :placeholder="'请选择' + item.name" clearable class="w100p" @change="getSelectData($event, item.prop)">
                <el-option v-for="(items, indexs) in item.typeObj.list" :key="indexs" :label="items.name"
                  :value="items.value" />
              </el-select>
              <el-date-picker v-if="item.type === 'TimePicker'" v-model="formData[`${item.prop}`]" type="datetime"
                class="w100p" value-format="yyyy-MM-dd HH:mm" :placeholder="'选择' + item.name"
                @change="timeEvent($event, item.prop)" />
            </el-form-item>
          </template>
          <!-- 选择发货商品 -->
          <el-divider v-if="nowChanceStau === 'add'" content-position="left">发货明细</el-divider>
          <el-form-item v-if="nowChanceStau === 'add'" label="发货商品 :" class="w50p">
            <el-checkbox-group v-model="formData.deliveryGoodsList" @change="chooseGoods">
              <el-checkbox v-for="(items, indexs) in deliveryGoodsList" :key="indexs" :label="items">{{
                items.materialName
              }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <div v-for="(orderDetail, index) in formData.deliveryDetailList" :key="orderDetail.key" class="w100p xunhuan">
            <div class="w100p goods">发货商品{{ index + 1 }}</div>
            <el-form-item label="商品名称 :" :prop="'deliveryDetailList.' + index + '.materialNo'" class="w50p" :rules="[
              {
                required: true,
                message: '商品名称不能为空',
                trigger: 'change',
              },
            ]">
              <el-select v-model="orderDetail.materialNo" placeholder="请选择商品（物料）名称" clearable disabled class="w100p"
                @change="getGoods($event, index)">
                <el-option v-for="(items, indexs) in materialList" :key="indexs" :label="items.materialName"
                  :value="items.materialNo" />
              </el-select>
            </el-form-item>

            <el-form-item label="发货仓库 :" :prop="'deliveryDetailList.' + index + '.stordocNo'" class="w50p">
              <el-select v-model="orderDetail.stordocNo" placeholder="请选择收货仓库" clearable disabled class="w100p">
                <el-option v-for="(items, indexs) in stordocList" :key="indexs" :label="items.stordocName"
                  :value="items.stordocNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="单位 :" :prop="'deliveryDetailList.' + index + '.castUnitNo'" class="w50p" :rules="[
              { required: true, message: '单位不能为空', trigger: 'change' },
            ]">
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" disabled clearable class="w100p">
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="应发货数量 :" :prop="'deliveryDetailList.' + index + '.shouldSendNum'"
              class="w50p numberUnit" :rules="[
                {
                  pattern:
                    /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                  message: '值该为大于0的数',
                  trigger: ['change', 'blur'],
                },
                { required: true, message: '数量不能为空', trigger: 'change' },
              ]">
              <el-input v-model="orderDetail.shouldSendNum" clearable class="one" disabled placeholder="请输入应发货数量" />
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" disabled class="two" clearable>
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="实发货数量 :" :prop="'deliveryDetailList.' + index + '.confirmQuantity'"
              class="w50p numberUnit" :rules="[
                {
                  pattern:
                    /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                  message: '值该为大于0的数',
                  trigger: ['change', 'blur'],
                },
                { required: true, message: '数量不能为空', trigger: 'change' },
              ]">
              <el-input v-model="orderDetail.confirmQuantity" class="one" clearable placeholder="请输入实发货数量" />
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" disabled class="two" clearable>
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="换算率 :" :prop="'deliveryDetailList.' + index + '.exchangeRate'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值该为大于0的数',
                trigger: ['change', 'blur'],
              },
              {
                required: true,
                message: '换算率不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.exchangeRate" clearable placeholder="请输入换算率" disabled />
            </el-form-item>
            <div class="zhu w50p">
              <el-form-item label="主数量&主单位 :" :prop="'deliveryDetailList.' + index + '.primaryQuantity'"
                style="width: 82%" :rules="[
                  {
                    required: true,
                    message: '数量不能为空',
                    trigger: 'change',
                  },
                  {
                    pattern: /^\d+$/,
                    message: '值该为正整数',
                    trigger: ['change', 'blur'],
                  },
                ]">
                <el-input v-model="orderDetail.primaryQuantity" clearable disabled placeholder="请输入主数量" />
              </el-form-item>
              <el-form-item :prop="'deliveryDetailList.' + index + '.unitNo'" style="width: 18%" :rules="[
                {
                  required: true,
                  message: '主单位不能为空',
                  trigger: 'change',
                },
              ]">
                <el-select v-model="orderDetail.unitNo" placeholder="请选择单位" disabled clearable>
                  <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                    :value="items.unitNo" />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="单价 :" :prop="'deliveryDetailList.' + index + '.price'" class="w50p" :rules="[
              { required: true, message: '单价不能为空', trigger: 'change' },
            ]">
              <el-input v-model="orderDetail.price" clearable disabled placeholder="请输入单价" />
            </el-form-item>
            <el-form-item label="折扣 :" :prop="'deliveryDetailList.' + index + '.discount'" class="w50p">
              <el-input v-model="orderDetail.discount" clearable disabled placeholder="请输入折扣" />
            </el-form-item>
            <el-form-item label="折扣额 :" :prop="'deliveryDetailList.' + index + '.discountPrice'" class="w50p">
              <el-input v-model="orderDetail.discountPrice" clearable disabled placeholder="请输入折扣额" />
            </el-form-item>
            <el-form-item label="价税合计 :" :prop="'deliveryDetailList.' + index + '.totalPrice'" class="w50p" :rules="[
              {
                required: true,
                message: '价税合计不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.totalPrice" clearable disabled placeholder="请输入价税合计" />
            </el-form-item>
            <el-form-item label="发货日期 :" :prop="'deliveryDetailList.' + index + '.sendTime'" class="w50p" :rules="[
              { required: true, message: '发货不能为空', trigger: 'change' },
            ]">
              <el-date-picker v-model="orderDetail.sendTime" type="datetime" value-format="yyyy-MM-dd HH:mm" clearable
                class="w100p" placeholder="请选择发货日期" />
            </el-form-item>
            <el-form-item label="发货地址 :" :prop="'deliveryDetailList.' + index + '.deliverAdd'" class="w50p" :rules="[
              {
                required: true,
                message: '发货地址不能为空',
                trigger: 'change',
              },
            ]">
              <el-select v-model="orderDetail.deliverAdd" placeholder="请选择发货地址" clearable class="w100p">
                <el-option v-for="(items, indexs) in addressList" :key="indexs" :label="items.spliceAddress"
                  :value="items.spliceAddress" />
              </el-select>
            </el-form-item>
            <el-form-item label="收货地址 :" :prop="'deliveryDetailList.' + index + '.creceiveaddr'" class="w50p" :rules="[
              {
                required: true,
                message: '收货地址不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.creceiveaddr" clearable class="w100p" placeholder="请输入收货地址" />
            </el-form-item>
            <el-form-item label="要求收货日期 :" :prop="'deliveryDetailList.' + index + '.arrivalTime'" class="w50p" :rules="[
              {
                required: true,
                message: '要求收货日期不能为空',
                trigger: 'change',
              },
            ]">
              <el-date-picker v-model="orderDetail.arrivalTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                clearable class="w100p" placeholder="请选择收货日期" />
            </el-form-item>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button v-if="nowChanceStau === 'add'" class="zh-button-two" type="primary" @click="save('formData')">保
            存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import { mymixin } from "@/utils/mixins";
import customerApi from "@/api/livestock-manage/sale-manage/customerManage"; // 客户
import unitApi from "@/api/basic-info-manage/unit-manage"; // 单位
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料
import saleOrderApi from "@/api/livestock-manage/sale-manage/sale-order"; // 销售订单
import saleOrderDetailApi from "@/api/livestock-manage/sale-manage/sale-order-detail"; // 销售订单明细
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage"; // 仓库
import personApi from "@/api/livestock-manage/personnel-cost-mansge/staff-manage"; // 人员
import deliveryNoticeApi from "@/api/livestock-manage/sale-manage/delivery";
import deliveryDetailApi from "@/api/livestock-manage/sale-manage/delivery-detail";
import addressApi from "@/api/livestock-manage/inventory/address/addressManage";
import { mapGetters } from "vuex";

export default {
  name: "SheepInformation",
  components: { SearchForm, TableData, BtnSlot, Pagination, MainSlot },
  mixins: [mymixin],
  data() {
    return {
      selectionList: [], //
      customerList: [], //供应商list
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      dataList: [],
      btnList: ["add"],
      formItemList: [
        {
          label: "销售订单号",
          type: "input",
          param: "saleOrderNo",
          isShow: true,
        },
        {
          selectOptions: [],
          label: "客户名称",
          type: "select",
          param: "customerNo",
          multiple: false,
          isShow: true,
        },
        {
          label: "发货员",
          param: "deliverName",
          isShow: true,
          type: "input",
        },
        {
          label: "收货人",
          param: "receiverName",
          isShow: true,
          type: "input",
        },
        {
          label: "发货日期",
          param: "sendTime",
          isShow: true,
          type: "date",
        },
      ], //搜索
      tableThead: [],
      // 配置项
      table_config: {
        isCheckBox: false,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "120",
          cols: [
            {
              label: "出库",
              type: "primary",
              flag: "goTo",
              handleRow: this.handleRow,
            },
          ],
        },
      },
      // =======================
      searchlist: {},
      tableColumn: [],
      addressList: [],
      forderStatus: 0,
      deliveryGoodsList: [],
      selectedStaffList: [],
      stordocList: [],
      unitList: [],
      materialList: [],
      personList: [],
      formData: {
        deliveryDetailList: [],
      },
      // selectValue 用于传递select的编号
      formDatalists: [
        {
          type: "Select",
          prop: "saleOrderNo",
          selectValue: "saleOrderNo", // input Select Checkbox TimePicker
          typeObj: {},
          name: "销售订单号",
          required: true,
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "customerName",
          selectValue: "customerNo",
          typeObj: {},
          name: "客户",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalNumber",
          typeObj: {},
          name: "总件数",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalQuantity",
          typeObj: {},
          name: "总数量",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "价税合计/元",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "",
          typeObj: {},
          name: "发货明细",
          edit: "edit",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "deliverName",
          typeObj: {},
          name: "发货人",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "deliverPhone",
          typeObj: {},
          name: "发货人联系方式",
          required: false,
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "sendTime",
          typeObj: {},
          name: "发货日期",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "receiverName",
          typeObj: {},
          name: "收货人",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "receiverPhone",
          typeObj: {},
          name: "收货人联系方式",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          notSearch: true,
        },
      ],
      rules: {},
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.deliveryDetailList) {
          //
        }
        sum(1);
        function sum(arr) {
          let s = 0;
          for (let i = arr.length - 1; i >= 0; i--) {
            s += parseInt(arr[i]);
          }
          return s;
        }
      },
    },
  },
  created() {
    let list = [];
    this.formDatalists.forEach((el) => {
      let obj = {
        isShow: true,
        label: el.name,
      };
      if (["发货明细"].includes(el.name)) {
        obj.slotName = "viewList";
      } else {
        obj.prop = el.prop;
      }
      list.push(obj);
    });
    this.tableThead = list;

    this.search();
    this.getMaterialList();
    this.getCustomerList();
    this.getstordocList();
    this.getUnitList();
    this.getOederList();
    this.getPersonList();
    this.getAddressList();
  },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "delete" && this.selectIndex === 0) {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      } else if (flag == "delete" && this.selectIndex !== 0) {
        this.$message.warning("审核通过不支持删除");
      }
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "goTo") {
        this.goTo(rowData)

      }

    },
    // 获取地址
    getAddressList() {
      addressApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.addressList = res.data;
        }
      });
    },
    // 跳转入库
    goTo(row) {
      this.$router.push({
        name: "out-storage",
        params: { deliveryNo: row.deliveryNo, isTo: "toAdd" },
      });
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then((res) => {
        if (res.code === 1) {
          this.materialList = res.data;
        }
      });
    },
    // 获取人员列表
    getPersonList() {
      personApi.getStaffListByCondition().then((res) => {
        if (res.code === 1) {
          this.personList = res.data;
          let list = [];
          res.data.forEach((item) => {
            list.push({
              name: item.person.name,
              value: item.personNo,
            });
          });
          // this.formDatalists.forEach((item, index) => {
          //   if (item.prop === "receiverName") {
          //     this.$set(this.formDatalists[index].typeObj, "list", list);
          //   }
          // });
        }
      });
    },
    // 获取销售所有订单
    getOederList() {
      saleOrderApi
        .conditionQuery({ completeStatus: true, forderStatus: 1 })
        .then((res) => {
          if (res.code === 1) {
            let list = [];
            res.data.forEach((item) => {
              list.push({
                name: item.saleOrderNo,
                value: item.saleOrderNo,
              });
            });
            this.formDatalists.forEach((item, index) => {
              if (item.prop === "saleOrderNo") {
                this.$set(this.formDatalists[index].typeObj, "list", list);
              }
            });
          }
        });
    },
    getCount(event, index) {
      let a = this.formData.deliveryDetailList[index].produceDate; // 生产日期
      let b = this.formData.deliveryDetailList[index].lifeDays; // 保质期
      let c = this.formData.deliveryDetailList[index].expirationDate; // 失效日期
      if (a && b) {
        let time = new Date(a.replace(/-/, "/"));
        let newDate = new Date(time.getTime() + b * (1000 * 60 * 60 * 24));
        console.log(newDate);
        let year = newDate.getFullYear();
        let mon = newDate.getMonth() + 1;
        let day = newDate.getDate();
        console.log(year, mon, day);
        let date = year + "-" + mon + "-" + day;
        this.$set(
          this.formData.deliveryDetailList[index],
          "expirationDate",
          date
        );
      }
      if (a && c) {
        let a1 = Date.parse(new Date(a));
        let a2 = Date.parse(new Date(c));
        let day = parseInt((a2 - a1) / (1000 * 60 * 60 * 24));
        this.$set(this.formData.deliveryDetailList[index], "lifeDays", day);
      }
    },
    // 获取仓库X
    getstordocList() {
      warehouseApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.stordocList = res.data;
        }
      });
    },
    // 获取单位列表X
    getUnitList() {
      unitApi.getPlantingUnitListByCondition({}).then((res) => {
        if (res.code === 1) this.unitList = res.data;
      });
    },
    // 获取客户
    getCustomerList() {
      customerApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          let list = [];
          // 提供表头搜索数据
          res.data.forEach((item) => {
            list.push({
              name: item.customerName,
              value: item.customerNo,
            });
          });
          this.formDatalists.forEach((item, index) => {
            if (item.prop === "customerName") {
              this.$set(this.formDatalists[index].typeObj, "list", list);
            }
          });
        }
      });
    },
    timeEvent(event, prop) {
      if (prop === "sendTime") {
        this.formData.deliveryDetailList.forEach((item, index) => {
          this.$set(this.formData.deliveryDetailList[index], "sendTime", event);
        });
      }
    },
    // 获取单个商品
    getGoods(event, index) {
      materialApi.getqueryList({ materialNo: event }).then((res) => {
        this.formData.deliveryDetailList[index].unitNo = res.data[0].unitNo;
        this.formData.deliveryDetailList[index].castUnitNo = res.data[0].unitNo;
      });
    },
    // 获取单个供应商
    getSelectData(event, prop) {
      // 获取单个销售订单
      if (prop === "saleOrderNo" && event) {
        saleOrderApi.numberQuery(event).then((res) => {
          if (res.code === 1) {
            this.formData = { ...res.data };
            // this.formData.totalVolume = Number(res.data.totalVolume);
            // this.formData.totalWeight = Number(res.data.totalWeight);
            this.getOrderDetailList(event);
          }
        });
      } else {
        return;
      }
    },
    // 获取订单详细列表
    getOrderDetailList(e) {
      saleOrderDetailApi.queryListBySaleOrderNo(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "deliveryGoodsList", []);
          this.deliveryGoodsList = res.data;
          this.$set(this.formData, "deliveryGoodsList", [
            this.deliveryGoodsList[0],
          ]);
          this.chooseGoods([this.deliveryGoodsList[0]]);
        }
      });
    },
    // 选择发货商品
    chooseGoods(e) {
      let price = 0;
      this.$set(this.formData, "deliveryDetailList", e);
      this.formData.deliveryDetailList.forEach((item, index) => {
        this.formData.deliveryDetailList[index].organizationNo =
          sessionStorage.organizationNo;
        this.$set(
          this.formData.deliveryDetailList[index],
          "shouldSendNum",
          item.confirmQuantity
        );
        this.$set(
          this.formData.deliveryDetailList[index],
          "arriveTime",
          this.formData.arriveTime
        );
        price += item.totalPrice;
      });
      this.$set(this.formData, "totalPrice", price);
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: {
          ...this.searchlist,
          sendTime:
            this.searchlist.sendTime && this.searchlist.sendTime + " 00:00:00",
        },
      };
      deliveryNoticeApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.total = data.totalElements;
          this.dataList = data.content;
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.saleOrderNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      deliveryNoticeApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          deliveryNoticeApi.numberDel(val).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    add() {
      this.formData = {};
      this.deliveryGoodsList = [];
      this.nowChanceStau = "add";
      this.titleText = "添加发货通知";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      saleOrderDetailApi.numberQuery(row.saleOrderNo).then((res) => {
        this.$set(this.formData, "deliveryDetailList", res.data);
      });
      this.nowChanceStau = "edit";
      this.titleText = "修改发货通知";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    lookInfo(e) {
      this.formData = {};
      deliveryDetailApi.queryListByDeliveryNo(e).then((res) => {
        if (res.code === 1) {
          this.$set(this.formData, "deliveryDetailList", res.data);
        }
      });
      this.nowChanceStau = "lookInfo";
      this.titleText = "查看发货明细";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "deliveryDetailList." + index + ".materialNo",
          "deliveryDetailList." + index + ".confirmQuantity",
          "deliveryDetailList." + index + ".castUnitNo",
          "deliveryDetailList." + index + ".unitNo",
          "deliveryDetailList." + index + ".exchangeRate",
          "deliveryDetailList." + index + ".primaryQuantity",
          "deliveryDetailList." + index + ".price",
          "deliveryDetailList." + index + ".packNum",
          "deliveryDetailList." + index + ".totalPrice",
          "deliveryDetailList." + index + ".address",
        ],
        (valid) => {
          if (!valid) {
            validateFieldList.push(valid);

            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every((item) => item === "")
            ) {
              saleOrderDetailApi.add(e).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  saleOrderDetailApi.numberQuery(e.saleOrderNo).then((res) => {
                    this.$set(this.formData, "orderDetailList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          saleOrderDetailApi.edit(e).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => { });
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          saleOrderDetailApi.numberQuery(e.saleOrderNo).then((res) => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              saleOrderDetailApi.numberDel(e.orderDetailNo).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.orderDetailList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => { });
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          // 添加仓库名称
          this.formData.deliveryDetailList.forEach((item, index) => {
            if (item.stordocNo) {
              this.stordocList.forEach((item1) => {
                if (item1.stordocNo === item.stordocNo) {
                  this.formData.deliveryDetailList[index].stordocName =
                    item1.stordocName;
                }
              });
            }
          });
          if (this.nowChanceStau === "edit") {
            deliveryNoticeApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            deliveryNoticeApi.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-dialog__wrapper .el-dialog .el-form-item .el-form-item__label {
  min-width: 140px;
}

::v-deep .el-form-item[data-v-3d395f82] {
  display: flex;
  margin-bottom: 10px;
  margin-right: 20px;
}

::v-deep .el-dialog__body {
  max-height: 66vh;
  overflow-y: auto;
}

::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item__content {
    display: flex;
    margin-right: 20px;
  }
}

.xunhuan {
  margin-bottom: 50px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }

  .editBox {
    z-index: 100;
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}
</style>
